import os
import logging.config

from flask import Flask
from flask_restplus import Api
from sqlalchemy import create_engine
from flask_jwt_extended import JWTManager
from decimal import Decimal
from datamaster import Db, Dict, AlchemyEncoder, DbPlus
from car import settings

from flask_jwt_extended import (
    jwt_required,
    get_jwt_identity
)

engine = create_engine(settings.SQLALCHEMY_DATABASE_URI, encoding='utf8', echo=True, pool_pre_ping=True)
db = Db(engine)
dbplus = DbPlus(db)

app = Flask(__name__)

# logging_conf_path = os.path.normpath(os.path.join(os.path.dirname(__file__), 'log.conf'))
# logging.config.fileConfig(logging_conf_path)
# log = logging.getLogger(__name__)

JWT_ACCESS_COOKIE_NAME = settings.JWT_ACCESS_COOKIE_NAME
JWT_REFRESH_COOKIE_NAME = settings.JWT_REFRESH_COOKIE_NAME

app.config['JWT_TOKEN_LOCATION'] = ['cookies']
app.config['JWT_ACCESS_COOKIE_PATH'] = '/'
app.config['JWT_REFRESH_COOKIE_PATH'] = '/'
# Disable CSRF protection for this example. In almost every case, this is a bad idea.
app.config['JWT_COOKIE_CSRF_PROTECT'] = False
app.config['JWT_SECRET_KEY'] = settings.JWT_SECRET_KEY
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = settings.JWT_ACCESS_TOKEN_EXPIRES
app.config['JWT_REFRESH_TOKEN_EXPIRES'] = settings.JWT_REFRESH_TOKEN_EXPIRES
app.config['JWT_ACCESS_COOKIE_NAME'] = JWT_ACCESS_COOKIE_NAME
app.config['JWT_REFRESH_COOKIE_NAME'] = JWT_REFRESH_COOKIE_NAME
app.config['SECRET_KEY'] = settings.SECRET_KEY

jwt = JWTManager(app)

auth_required = jwt_required


def auth_user():
    return Dict(get_jwt_identity())


class ExtendEncoder(AlchemyEncoder):
    def default(self, obj):
        if isinstance(obj, Decimal):
            return int(obj)
        else:
            return super().default(obj)


# 配置默认的JSON序列化
app.config['RESTPLUS_JSON'] = {
    'cls': ExtendEncoder,
    'check_circular': False,
    'indent': 2,
    'separators': (', ', ': ')
}

api = Api(version='1.0.0', title='Sale Manager API',
          description='Powered by DataMaster')

api.app = app
api.init_app(app)
